package com.java.simple.study.juc.p3.exercise;

import com.java.simple.study.jvm.sugar.A;
import lombok.extern.slf4j.Slf4j;

import java.util.Random;

/**
 * @author zhoujl
 * @date 2022/5/7 22:30
 * @desc
 */
@Slf4j(topic = "c.ExerciseTransfer")
public class ExerciseTransfer {

    public static void main(String[] args) throws InterruptedException {
        Account a = new Account(1000);
        Account b = new Account(1000);
        // 开启两个线程 模拟两个账户相互转账1000次
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                a.transfer(b, randomAmount());
            }
        }, "t1");

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 1000; i++) {
                b.transfer(a, randomAmount());
            }
        }, "t2");

        t1.start();
        t2.start();
        t1.join();
        t2.join();
        log.debug("after transfer total:{}", (a.getMoney() + b.getMoney()));
    }


    static Random random = new Random();

    public static int randomAmount() {
        return random.nextInt(100) + 1;
    }
}


class Account {
    private int money;

    public Account(int money) {
        this.money = money;
    }

    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }

    public /*synchronized*/ void transfer(Account target, int amount) {
        // 涉及到两个对象的竞态条件 要用锁类对象的方式
        synchronized (Account.class) {
            if (this.money > amount) {
                this.setMoney(this.getMoney() - amount);
                target.setMoney(target.getMoney() + amount);
            }
        }
    }
}